package com.example.weixintest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class ExpandAdapter extends RecyclerView.Adapter<ExpandAdapter.ExpandViewHolder> {
    private List<String> list;
    private View inflater;
    private Context context;

    private int expandedPosition = -1;
    private ExpandViewHolder mViewHolder;

    public ExpandAdapter(Context context, List<String> list) {
        this.context=context;
        this.list=list;
    }

    @Override
    public ExpandAdapter.ExpandViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        inflater= LayoutInflater.from(context).inflate(R.layout.expand_contract,parent,false);
        ExpandViewHolder expandViewHolder = new ExpandViewHolder(inflater);
        return expandViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ExpandAdapter.ExpandViewHolder holder, int position) {
        holder.tvParent.setText(list.get(position));
        holder.tvChild.setText(list.get(position) + "申请添加你为好友");

        final boolean isExpanded = position == expandedPosition;
        holder.rlChild.setVisibility(isExpanded ? View.VISIBLE : View.GONE);
        holder.rlParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mViewHolder != null) {
                    mViewHolder.rlChild.setVisibility(View.GONE);
                    notifyItemChanged(expandedPosition);
                }
                expandedPosition = isExpanded ? -1 : holder.getAdapterPosition();
                mViewHolder = isExpanded ? null : holder;
                notifyItemChanged(holder.getAdapterPosition());
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class ExpandViewHolder extends RecyclerView.ViewHolder{
        RelativeLayout rlParent, rlChild;
        TextView tvParent, tvChild;
        public ExpandViewHolder(View itemView) {
            super(itemView);
            rlParent = itemView.findViewById(R.id.rl_parent);
            rlChild = itemView.findViewById(R.id.rl_child);
            tvParent = itemView.findViewById(R.id.tv_parent);
            tvChild = itemView.findViewById(R.id.tv_child);
        }
    }
}
